<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.userId"
        clearable
        class="filter-item"
        style="width: 200px;"
        placeholder="请输入用户ID"
      />
      <el-input
        v-model="listQuery.orderSn"
        clearable
        class="filter-item"
        style="width: 200px;"
        placeholder="请输入订单编号"
      />
      <el-select
        v-model="listQuery.orderStatus"
        style="width: 200px"
        class="filter-item"
        placeholder="请选择订单状态"
      >
        <el-option
          v-for="(item,key) in statusMap"
          :key="key"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button
        v-permission="['GET /admin/order/list']"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >查找</el-button>
      <el-button
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleDownload"
      >导出</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" min-width="100" label="订单编号" prop="orderSn" />

      <el-table-column align="center" label="用户ID" prop="userId" />

      <el-table-column align="center" label="订单状态" prop="orderStatus">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.orderStatus | orderStatusFilter }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="订单金额" prop="orderPrice" />

      <el-table-column align="center" label="支付金额" prop="actualPrice" />

      <el-table-column align="center" label="支付时间" prop="payTime" />

      <el-table-column align="center" label="物流单号" prop="shipSn" />

      <el-table-column align="center" label="物流渠道" prop="shipChannel" />

      <el-table-column align="center" label="操作" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-permission="['POST /admin/order/refund']"
            type="primary"
            size="mini"
            @click="comformDrawback(scope.row)"
          >确认退款</el-button>
          <el-button
            v-permission="['POST /admin/order/refund']"
            type="primary"
            size="mini"
            @click="cancelDrawback(scope.row)"
          >拒绝退款</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.current"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
  </div>
</template>

<script>
import {
  detailOrder,
  listOrder,
  listChannel,
  refundOrder,
  shipOrder
} from '@/api/order';
import Pagination from '@/components/Pagination'; // Secondary package based on el-pagination
import checkPermission from '@/utils/permission'; // 权限判断函数

const statusMap = [
  { label: '用户取消', value: -1 },
  { label: '系统取消', value: -3 },
  { label: '已超时团购', value: -4 },
  { label: '申请退款', value: -5 },
  { label: '已退款', value: -6 },
  { label: '未付款', value: 1 },
  { label: '待发货', value: 2 },
  { label: '待收货', value: 3 },
  { label: '用户收货', value: 4 },
  { label: '完成交易', value: 5 },
  { label: '已付款团购', value: 6 }
];

export default {
  name: 'Order',
  components: { Pagination },
  filters: {
    orderStatusFilter(status) {
      return statusMap[status];
    }
  },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        current: 1,
        size: 20,
        name: undefined,
        content: undefined,
        orderBy: 'add_time',
        sort: 'desc'
      },
      statusMap,
      orderDialogVisible: false,
      orderDetail: {
        ordersVO: {},
        user: {},
        orderGoods: []
      },
      shipForm: {
        orderId: undefined,
        shipChannel: undefined,
        shipSn: undefined
      },
      shipDialogVisible: false,
      refundForm: {
        orderId: undefined,
        refundMoney: undefined
      },
      refundDialogVisible: false,
      downloadLoading: false,
      channels: []
    };
  },
  created() {
    this.getList();
    this.getChannel();
  },
  methods: {
    checkPermission,
    getList() {
      this.listLoading = true;
      listOrder(this.listQuery)
        .then(response => {
          this.list = response.data.data.list;
          this.total = response.data.data.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });
    },
    comformDrawback(row) {},
    cancelDrawback(row) {},
    getChannel() {
      listChannel().then(response => {
        this.channels = response.data.data;
      });
    },
    handleFilter() {
      this.listQuery.current = 1;
      this.getList();
    },
    handleDetail(row) {
      detailOrder(row.id).then(response => {
        this.orderDetail = response.data.data;
      });
      this.orderDialogVisible = true;
    },
    handleShip(row) {
      this.shipForm.orderId = row.id;
      this.shipForm.shipChannel = row.shipChannel;
      this.shipForm.shipSn = row.shipSn;

      this.shipDialogVisible = true;
      this.$nextTick(() => {
        this.$refs['shipForm'].clearValidate();
      });
    },
    confirmShip() {
      this.$refs['shipForm'].validate(valid => {
        if (valid) {
          shipOrder(this.shipForm)
            .then(response => {
              this.shipDialogVisible = false;
              this.$notify.success({
                title: '成功',
                message: '确认发货成功'
              });
              this.getList();
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              });
            });
        }
      });
    },
    handleRefund(row) {
      this.refundForm.orderId = row.id;
      this.refundForm.refundMoney = row.actualPrice;

      this.refundDialogVisible = true;
      this.$nextTick(() => {
        this.$refs['refundForm'].clearValidate();
      });
    },
    confirmRefund() {
      this.$refs['refundForm'].validate(valid => {
        if (valid) {
          refundOrder(this.refundForm)
            .then(response => {
              this.refundDialogVisible = false;
              this.$notify.success({
                title: '成功',
                message: '确认退款成功'
              });
              this.getList();
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              });
            });
        }
      });
    },
    handleDownload() {
      this.downloadLoading = true;
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          '订单ID',
          '订单编号',
          '用户ID',
          '订单状态',
          '是否删除',
          '收货人',
          '收货联系电话',
          '收货地址'
        ];
        const filterVal = [
          'id',
          'orderSn',
          'userId',
          'orderStatus',
          'isDelete',
          'consignee',
          'mobile',
          'address'
        ];
        excel.export_json_to_excel2(tHeader, this.list, filterVal, '订单信息');
        this.downloadLoading = false;
      });
    },
    printOrder() {
      this.$print(this.$refs.print);
      this.orderDialogVisible = false;
    }
  }
};
</script>
